package com.zzh.lib.recorder.ui.frag;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageView;

import com.zzh.lib.recorder.AudioFormat;
import com.zzh.lib.recorder.HMediaRecorder;
import com.zzh.lib.recorder.HMediaRecorderParams;
import com.zzh.lib.recorder.HRecorder;
import com.zzh.lib.recorder.R;
import com.zzh.lib.recorder.def.IRecorder;
import com.zzh.lib.recorder.def.OnRecorderCallback;
import com.zzh.lib.recorder.view.HSDKAnimationView;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * Created by ZZH on 2021/11/30.
 *
 * @Date: 2021/11/30
 * @Email: zzh_hz@126.com
 * @QQ: 1299234582
 * @Author: zzh
 * @Description: 音频录制
 */
public class AudioRecordFragment extends Fragment implements HMediaRecorderParams.OnMaxAmplitudeListener, OnRecorderCallback {

    public static final String AUDIO_FORMAT = "AUDIO_FORMAT";

    protected HSDKAnimationView voice;
    protected Chronometer chronometer;
    protected File filePath;
    private long duration;
    ImageView iv_record;
    IRecorder mRecorder;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View inflate = inflater.inflate(R.layout.h_lib_frag_audio_recorder, container, false);
        voice = inflate.findViewById(R.id.voice);
        chronometer = inflate.findViewById(R.id.chronometer);
        iv_record = inflate.findViewById(R.id.h_record_control_view);
        iv_record.setOnClickListener(v -> onViewClicked());
        voice.startInitializingAnimation();
        voice.startPreparingAnimation();

        initRecorder();


        return inflate;
    }

    protected void initRecorder() {
        filePath = new File(getActivity().getCacheDir(), System.currentTimeMillis() + ".aac");

        Bundle arguments = getArguments();
        String audioFormat = "";
        if (arguments != null) {
            audioFormat = arguments.getString(AUDIO_FORMAT, "AAC");
        } else {
            audioFormat = "AAC";
        }


        HMediaRecorderParams params = new HMediaRecorderParams();
        if (Build.VERSION.SDK_INT > 28) {
            params.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
        } else {
            params.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        }
        params.setAudioSamplingRate(44100);
        params.setAudioEncodingBitRate(64000);
        params.setAudioChannels(1);
        params.setOnMaxAmplitudeListener(this);
        HRecorder.getInstance().setRecorderParams(params);
        if ("mp3".equalsIgnoreCase(audioFormat)) {
            HRecorder.getInstance().setAudioFormat(AudioFormat.MP3);
        } else if ("amr".equalsIgnoreCase(audioFormat)) {
            HRecorder.getInstance().setAudioFormat(AudioFormat.AMR);
        } else {
            HRecorder.getInstance().setAudioFormat(AudioFormat.AAC);
        }
        mRecorder = HRecorder.getInstance().init();

        HRecorder.getInstance().setOnRecorderCallback(this);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            getActivity().runOnUiThread(() -> {
                try {
                    Float obj = (Float) msg.obj;
                    Log.d("------", String.valueOf(obj));
                    voice.setCurrentDBLevelMeter(obj);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    };

    public void onViewClicked() {

        if (mRecorder != null){
            if (HRecorder.getInstance().getState() == HMediaRecorder.State.Recording) {
                mRecorder.stop();
                chronometer.stop();
                voice.resetAnimation();
                iv_record.setImageResource(R.drawable.h_start_video);
                Intent intent = new Intent();
                intent.putExtra("filePath", filePath.getAbsolutePath());
                intent.putExtra("fileDuration", duration);
                getActivity().setResult(Activity.RESULT_OK, intent);
                getActivity().finish();
            } else {
                iv_record.setImageResource(R.drawable.h_stop_video);
                chronometer.start();
                mRecorder.start(filePath);
                voice.startRecordingAnimation();
            }
        }


    }

    @Override
    public void onMaxAmplitude(double amp) {
        Message msg = mHandler.obtainMessage(0);
        msg.obj = (float) amp;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onDestroy() {
        HRecorder.getInstance().release();
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    @Override
    public void onRecordSuccess(File file, long duration) {
        this.duration = duration;
        filePath = file.getAbsoluteFile();
    }
}
